//
//  CardDetailViewController.m
//  jiyujiaProgram
//
//  Created by NiKi on 15/10/31.
//  Copyright © 2015年 中良 赵. All rights reserved.
//

#import "CardDetailViewController.h"
#import "CardDetailCell.h"
#import "HotCell.h"
#import "CardModel.h"

#import "CreatCardViewController.h"
#import "CardCommentViewController.h"

@interface CardDetailViewController () <UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>

@property (nonatomic, copy) NSString *imageId;
@property (nonatomic, copy) NSString *imageUrl;

@end

@implementation CardDetailViewController
{
//    UIScrollView *_scrollView;
    UIImageView *_circleHeadImage;
    UIView *_topView;
    UILabel *_nameLabel;
    UILabel *_topLabel;
    UIButton *_addButton;
    UITableView *_tableView;
    
    VOSegmentedControl *_segmentControl;
    
    MemberModel *_memberModel;
    TeacherModel *_teacherModel;
    
    NSMutableArray *_dataArray;
    NSMutableArray *_topArray;
    
    UIActionSheet *_photoActionSheet;
    NSData *_imageData;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatNavigationBarWithImage:nil title:self.circle_name];
    [self creatNavigationBarLeftItemWithLeftTitle:nil LeftImage:ECIMAGENAME(@"back_button.png")];
    [self creatNavigationBarRightItemWithRightTitle:nil RightImage:ECIMAGENAME(@"mine_photo.png")];
    self.navcImageView.alpha = 0;
    
//    [self creatScrollView];
    [self creatTopView];
    [self creatChooseView];
    [self creatTableView];
    [self creatAddCardButton];

    [self.view bringSubviewToFront:self.navcImageView];
    [self.view bringSubviewToFront:self.leftImageView];
    [self.view bringSubviewToFront:self.leftButton];
    [self.view bringSubviewToFront:self.rightImageView];
    [self.view bringSubviewToFront:self.rightButton];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self loadUserInfo];
    [self segmentClick:_segmentControl];
    
    [_circleHeadImage sd_setImageWithURL:[NSURL URLWithString:_memberModel.forum_background_imgUrl] placeholderImage:ECIMAGENAME(@"mine_top_bg.png")];
}


- (void)leftBtnClick:(id)leftSender
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)rightBtnClick:(id)rightSender
{
    _photoActionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"我的相册", @"相机",nil];
    [_photoActionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet == _photoActionSheet){
        switch (buttonIndex)
        {
            case 0:
            {
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
                {
                    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                    picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                    picker.delegate = self;
                    picker.allowsEditing = YES;
                    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    [self presentViewController:picker animated:YES completion:nil];
                }
            }
                break;
                
            case 1:
            {
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
                {
                    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                    picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                    picker.delegate = self;
                    picker.allowsEditing = YES;
                    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    [self presentViewController:picker animated:YES completion:nil];
                }
            }
                break;
                
            default:
                break;
        }
    }
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
//    _circleHeadImage.image = image;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    
    dispatch_async(queue, ^{
        
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
        {
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        }
        
        if (UIImagePNGRepresentation(image))
        {
            UIImage *newImage = [ECHelper imageWithImageSimple:image scaledToSize:CGSizeMake(320.0f, 320.0f)];
            _imageData = UIImagePNGRepresentation(newImage);
        }
        else
        {
            UIImage *newImage = [ECHelper imageWithImageSimple:image scaledToSize:CGSizeMake(320.0f, 320.0f)];
            _imageData = UIImageJPEGRepresentation(newImage, 0.75);
        }
        
    });
    
#warning ******************POSTPIC********************
    [self dismissViewControllerAnimated:YES completion:^{
        
        NSString *strRandomName = [NSString stringWithFormat:@"iOS_uploadImage_%d.jpg",arc4random_uniform(10000)];
        
        NSArray *files = @[
                           @{
                               @"name": strRandomName,
                               @"file": _imageData ,
                               @"key": @"image",
                               @"type": @"multipart/form-data"
                               }
                           ];
        
        [[HttpManager defaultManager] uploadToUrl:RequestURL(POSTPIC) params:nil files:files complete:^(BOOL successed, NSDictionary *result) {
            if (successed) {
                if ([result[@"errCode"] integerValue] == 0) {
                    [[HttpManager defaultManager] postRequestToUrl:RequestURL(UPDATEMINE) params:@{@"member_Id":_memberModel.member_Id,@"forum_background_imgId":result[@"pictures_ID"],}complete:^(BOOL successed, NSDictionary *result) {
                        if (successed) {
                            
                            UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
                            userInfo.memberModel.forum_background_imgUrl = result[@"forum_background_imgUrl"];
                            [userInfo saveUserInfoToSanbox];
                            [_circleHeadImage sd_setImageWithURL:[NSURL URLWithString:result[@"forum_background_imgUrl"]] placeholderImage:ECIMAGENAME(@"mine_top_bg.png")];
                            SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, nil);
                        }
                    }];
                }else{
                    SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, nil);
                }
            }
        }];
    }];
}

//- (void)creatScrollView
//{
//    CGRect rect = [[UIApplication sharedApplication] statusBarFrame];
//    
//    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, -rect.size.height, ECSCREEN_W, ECSCREEN_H + rect.size.height)];
//    _scrollView.delegate = self;
//    _scrollView.contentSize = CGSizeMake(ECSCREEN_W, 240);
//    _scrollView.backgroundColor = BG_COLOR;
//    _scrollView.showsVerticalScrollIndicator = NO;
//    [self.view addSubview:_scrollView];
//}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    CGRect rect = [[UIApplication sharedApplication] statusBarFrame];
//    CGFloat yOffset   = scrollView.contentOffset.y;
//    
//    NSLog(@"****%f*****",yOffset);
//    self.navcImageView.alpha = yOffset/(200 - 64 - rect.size.height);
//    NSLog(@"%f",yOffset/(200 - 64 - rect.size.height));
//}

- (void)loadUserInfo
{
    UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
    [userInfo loadUserInfoFromSanbox];
    _memberModel = userInfo.memberModel;
    _teacherModel = userInfo.teacherModel;
}


- (void)creatTopView
{
    _circleHeadImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ECSCREEN_W, 200)];
    _circleHeadImage.image = ECIMAGENAME(@"mine_top_bg.png");
    [self.view addSubview:_circleHeadImage];
    
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ECSCREEN_W, 200)];
    _topView.backgroundColor = ECCOLOR(0, 0, 0, .5);
    [_circleHeadImage addSubview:_topView];
    
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 70, ECSCREEN_W, 20)];
    _nameLabel.text = self.circle_name;
    _nameLabel.textColor = ECCOLOR(255, 255, 255, 1);
    _nameLabel.font = [UIFont systemFontOfSize:15.f];
    _nameLabel.textAlignment = NSTextAlignmentCenter;
    [_topView addSubview:_nameLabel];
    
    
    _topLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, ECSCREEN_W, 20)];
    _topLabel.text = @"帖子：1000          成员：999";
    _topLabel.textColor = ECCOLOR(255, 255, 255, 1);
    _topLabel.font = [UIFont systemFontOfSize:13.f];
    _topLabel.textAlignment = NSTextAlignmentCenter;
    [_topView addSubview:_topLabel];
    
    _addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _addButton.frame = CGRectMake((ECSCREEN_W - 80)/2, 140, 80, 30);
    _addButton.backgroundColor = ECCOLOR(0, 0, 0, .8);
    [_addButton setTitle:@"已加入" forState:UIControlStateNormal];
    [_addButton setTitleColor:ECCOLOR(255, 255, 255, 1) forState:UIControlStateNormal];
    _addButton.titleLabel.font = [UIFont systemFontOfSize:13.f];
    _addButton.clipsToBounds = YES;
    _addButton.layer.cornerRadius = 8;
    [_topView addSubview:_addButton];
}


- (void)creatChooseView
{
    _segmentControl = [[VOSegmentedControl alloc] initWithSegments:@[@{
                                                                         @"text":@"精华区"
                                                                         },@{
                                                                         @"text":@"全部帖子"
                                                                         }]];
    _segmentControl.frame = CGRectMake(0, 200, ECSCREEN_W, 40);
    _segmentControl.animationType = VOSegCtrlAnimationTypeSmooth;
    _segmentControl.contentStyle = VOContentStyleTextAlone;
    _segmentControl.indicatorStyle = VOSegCtrlIndicatorStyleBottomLine;
    _segmentControl.allowNoSelection = NO;
    _segmentControl.scrollBounce = NO;
    _segmentControl.selectedTextFont = [UIFont systemFontOfSize:15];
    _segmentControl.selectedIndicatorColor = NAVC_COLOR;
    _segmentControl.textColor = ECCOLOR(0, 0, 0, 1);
    _segmentControl.selectedTextColor = NAVC_COLOR;
    _segmentControl.selectedBackgroundColor = ECCOLOR(255, 255, 255, 1);
    _segmentControl.backgroundColor = ECCOLOR(255, 255, 255, 255);
    _segmentControl.indicatorThickness = 2;
    _segmentControl.indicatorCornerRadius = 15;
    [_segmentControl addTarget:self action:@selector(segmentClick:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_segmentControl];
}

- (void)segmentClick:(VOSegmentedControl *)segment
{
    switch (segment.selectedSegmentIndex) {
        case 0:
        {
            [self creatFirstHttpRequest];
        }
            break;
        case 1:
        {
            [self creatSecondHttpRequest];
        }
            break;
            
        default:
            break;
    }
}


- (void)creatFirstHttpRequest
{
    NSDictionary *param = @{
                            @"circle_id":self.circle_Id,
                            @"member_id":_memberModel.member_Id,
                            };
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(CARD) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            [CardModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"CardData",
                         };
            }];
            
            if (_dataArray) {
                [_dataArray removeAllObjects];
            }else{
                _dataArray = [[NSMutableArray alloc] init];
            }
            
            CardModel *card = [[CardModel alloc] init];
            card = [CardModel objectWithKeyValues:result];
            [_dataArray addObjectsFromArray:card.data];
            [_tableView reloadData];
        }
    }];
}


- (void)creatSecondHttpRequest
{
    NSDictionary *param = @{
                            @"circle_id":self.circle_Id,
                            };
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(CARD) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            [CardModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"CardData",
                         };
            }];
            
            if (_dataArray) {
                [_dataArray removeAllObjects];
            }else{
                _dataArray = [[NSMutableArray alloc] init];
            }
            
            if (_topArray) {
                [_topArray removeAllObjects];
            }else{
                _topArray = [[NSMutableArray alloc] init];
            }
            
            CardModel *card = [[CardModel alloc] init];
            card = [CardModel objectWithKeyValues:result];
            [_dataArray addObjectsFromArray:card.data];
            
            for (CardData *data in card.data) {
                if (data.is_top) {
                    [_topArray addObject:data];
                }
            }
            [_tableView reloadData];
        }
    }];
}


- (void)creatTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 240, ECSCREEN_W, ECSCREEN_H - 240) style:UITableViewStylePlain];
    _tableView.backgroundColor = BG_COLOR;
    [self.view addSubview:_tableView];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.tableFooterView = [[UIView alloc]init];
    
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ((_segmentControl.selectedSegmentIndex == 1) &&(indexPath.section == 0) && (_topArray.count > 0)) {
        return 40.f;
    }else{
        return 90.f;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ((_segmentControl.selectedSegmentIndex == 1) && (_topArray.count > 0)&&(section == 0)) {
        return _topArray.count;
    }else{
        return 1;
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ((_segmentControl.selectedSegmentIndex == 1) && (_topArray.count > 0)) {
        return _dataArray.count + 1;
    }else{
        return _dataArray.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ECSCREEN_W, 5)];
    view.backgroundColor = BG_COLOR;
    return view;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ((_segmentControl.selectedSegmentIndex == 1) &&(indexPath.section == 0) && (_topArray.count > 0)) {
        static NSString *reuseIdentifier = @"hotCell";
        HotCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (nil == cell) {
            NSArray *arr = [[NSBundle mainBundle]loadNibNamed:@"HotCell" owner:nil options:nil];
            for (NSObject *obj in arr) {
                if ([obj isKindOfClass:[HotCell class]]) {
                    cell = (HotCell *)obj;
                    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                        [cell setSeparatorInset:UIEdgeInsetsZero];
                    }
                    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                        [cell setLayoutMargins:UIEdgeInsetsZero];
                    }
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    break;
                }
            }
        }
        [cell setCellWithModel:_topArray WithIndexPath:indexPath];
        return cell;
    }else{
        static NSString *reuseIdentifier = @"cardDetailCell";
        CardDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (nil == cell) {
            NSArray *arr = [[NSBundle mainBundle]loadNibNamed:@"CardDetailCell" owner:nil options:nil];
            for (NSObject *obj in arr) {
                if ([obj isKindOfClass:[CardDetailCell class]]) {
                    cell = (CardDetailCell *)obj;
                    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                        [cell setSeparatorInset:UIEdgeInsetsZero];
                    }
                    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                        [cell setLayoutMargins:UIEdgeInsetsZero];
                    }
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    break;
                }
            }
        }
        [cell setCellWithModel:_dataArray WithIndexPath:indexPath isHidden:NO];
        return cell;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CardCommentViewController *vc = [[CardCommentViewController alloc] init];
    if ((_segmentControl.selectedSegmentIndex == 1)&&(indexPath.section == 0)&&(_topArray.count > 0)) {
        CardData *data = _topArray[indexPath.row];
        vc.data = data;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        CardData *data = _dataArray[indexPath.section];
        vc.data = data;
        [self.navigationController pushViewController:vc animated:YES];
    }
}



- (void)creatAddCardButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(ECSCREEN_W - 50, ECSCREEN_H - 60, 40, 40);
    [button setBackgroundImage:ECIMAGENAME(@"addcard.png") forState:UIControlStateNormal];
    [button addTarget:self action:@selector(addCardClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}


- (void)addCardClick:(UIButton *)button
{
    CreatCardViewController *vc = [[CreatCardViewController alloc] init];
    vc.circleId = self.circle_Id;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
